package wymiana.service;

import java.util.List;

import org.hibernate.Hibernate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import wymiana.dao.UploadedFileDao;
import wymiana.domain.UploadedFiles;
import wymiana.domain.User;

@Service("uploadedFileService")
@Transactional
public class UploadedFileService {

	@Autowired
	private UploadedFileDao uploadedFileDao;

	public void create(UploadedFiles uploadedFile) {
		uploadedFileDao.save(uploadedFile);
	}

	public List<UploadedFiles> getPersonalFiles(User u) {
		List<UploadedFiles> files = uploadedFileDao.getPersonalFiles(u);
		if (files != null) {
			for (UploadedFiles f : files) {
				Hibernate.initialize(f.getDgroup());
			}
		}
		return files;
	}

	public List<UploadedFiles> getAllUploadedFiles() {
		List<UploadedFiles> files = uploadedFileDao.getAll();
		if (files != null) {
			for (UploadedFiles f : files) {
				Hibernate.initialize(f.getDgroup());
			}
		}
		return files;
	}

	public UploadedFiles getUploadedFile(int p_id) {
		UploadedFiles f = uploadedFileDao.getUploadedFileById(p_id);
		try {
			Hibernate.initialize(f.getCreateUser());
			Hibernate.initialize(f.getDgroup());
			Hibernate.initialize(f.getDgroup().getDepartment());
			Hibernate.initialize(f.getDgroup().getDepartment().getSchool());
		} catch (Exception e) {

		}
		return f;
	}

	public void updateUploadedFile(UploadedFiles p) {
		uploadedFileDao.merge(p);
	}

	public void deleteFileByID(int f_id) {
		UploadedFiles f = uploadedFileDao.getById(f_id);
		uploadedFileDao.delete(f);
	}

}
